package com.dream.config;

import com.dream.net.socket.TcpRawPackageDecoder;
import com.dream.net.socket.TcpRawPackageEncoder;
import com.dream.net.socket.base.SocketController;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Configuration
public class SocketConfig extends ChannelInitializer<SocketChannel>{
    
    @Value("${socket.port}")
    private short listenPort;
    
    @Resource private SocketController socketController;
    
    @PostConstruct
    private void start() throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(this);
        serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        // 绑定端口，开始接收进来的连接
        serverBootstrap.bind(listenPort).sync();
    }
    
    @Override
    protected void initChannel(SocketChannel ch) {
    	ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("decoder", new TcpRawPackageDecoder());
        pipeline.addLast("encoder", new TcpRawPackageEncoder());
		pipeline.addLast("handler", socketController);
    }
    
}
